"""
206. 反转链表
简单
相关标签
premium lock icon
相关企业
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。


示例 1：


输入：head = [1,2,3,4,5]
输出：[5,4,3,2,1]
示例 2：


输入：head = [1,2]
输出：[2,1]
示例 3：

输入：head = []
输出：[]


提示：

链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000


进阶：链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题？
"""
from typing import Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head
        cur = head
        next = head.next
        cur.next = None
        while next:
            tmp = next.next
            next.next = cur
            cur = next
            next = tmp
        return cur

    def reverseList_res1(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre


def create_linked_list(values):
    """根据值列表创建链表"""
    if not values:
        return None
    head = ListNode(values[0])
    current = head
    for i in range(1, len(values)):
        current.next = ListNode(values[i])
        current = current.next
    return head


def linked_list_to_list(head):
    """将链表转换为值列表"""
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result


if __name__ == '__main__':
    # 测试用例1: [1,2,3,4,5]
    head1 = create_linked_list([1, 2, 3, 4, 5])
    solution = Solution()
    # result1 = solution.reverseList(head1)
    result1 = solution.reverseList_res1(head1)
    print(linked_list_to_list(result1))  # 输出: [5, 4, 3, 2, 1]
    print(linked_list_to_list(result1))  # 输出: [5, 4, 3, 2, 1]

    # # 测试用例2: [1,2]
    # head2 = create_linked_list([1, 2])
    # result2 = solution.reverseList(head2)
    # print(linked_list_to_list(result2))  # 输出: [2, 1]
    #
    # # 测试用例3: []
    # head3 = create_linked_list([])
    # result3 = solution.reverseList(head3)
    # print(linked_list_to_list(result3))  # 输出: []